/*
 * This class is called from the selectVariable class when user select show deshboard button.
 * here we have background thread which will be stared as soon as activity started and stop as activity finished.
 * This will continuously get range of variable and according to it, it will show green light for normal and red light for 
 * alert or not normal.
 */
package com.fipl.taksar;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DeshboardActivity extends Activity {
	
	private String dbName;
	private int sleepTime = 100;
	private ArrayList<String> statusArrayList = new ArrayList<String>();		// will store original data of the status ('normal','not normal', 'alert')
	private ArrayList<Boolean> statusBoolArrayList = new ArrayList<Boolean>();	// will store status about the particular data (true if 'normal', false if 'alert' or 'not normal')
	private ArrayList<String> listArrayList = new ArrayList<String>();			// will store dash board variable list 
	//arreglo de indices 
	private ArrayList<Integer> indexArrayList = new ArrayList<Integer>();
	private String status="test";
	private String listArr[];
	private StringBuffer jsonText = null;
	private Thread backgroundThread;
	private boolean running = false;
	private boolean handlerFlag = false;
	private JSONArray jsonArray;
	private MyArrayAdapter myArrayAdapter;	
	private LinearLayout linearLayout;
	private ListView listView;
	// this array will be used when user select all the variable from the select variable.
	private String [] sensor={"Temperature_1","Humidity_1", "Temperature_2", "Humidity_2", 
			"Temperature_3", "Humidity_3" ,"Temperature_4","Humidity_4" ,"Voltage_1A",
			"Voltage_1B","Voltage_1C", "Current_1A","Current_1B","Current_1C","Voltage_2A",
			"Voltage_2B","Voltage_2C", "Current_2A","Current_2B","Current_2C","Voltage_3A",
			"Voltage_3B","Voltage_3C", "Current_3A","Current_3B","Current_3C","Voltage_4A",
			"Voltage_4B","Voltage_4C", "Current_4A","Current_4B","Current_4C","Voltage_5A",
			"Voltage_5B","Voltage_5C", "Current_5A","Current_5B","Current_5C","Voltage_6A",
			"Voltage_6B","Voltage_6C", "Current_6A","Current_6B","Current_6C","Voltage_7A",
			"Voltage_7B","Voltage_7C","Voltage_8A","Voltage_8B","Voltage_8C","Diesel_1",
			"Diesel_2","PSTemperature_1","PSTemperature_2","DigitalInput_1","DigitalInput_2",
			"DigitalInput_3","DigitalInput_4","DigitalInput_5","DigitalInput_6","DigitalInput_7",
			"DigitalInput_8","DigitalInput_9","DigitalInput_10","DigitalInput_11","DigitalInput_12",
			"DigitalInput_13","DigitalInput_14","DigitalInput_15","DigitalInput_16","DigitalInput_17",
			"DigitalInput_18","DigitalInput_19","DigitalInput_20","DigitalInput_21","DigitalInput_22",
			"DigitalInput_23","DigitalInput_24","DigitalOutput_1","DigitalOutput_2","DigitalOutput_3",
			"DigitalOutput_4","DigitalOutput_5","DigitalOutput_6","DigitalOutput_7","DigitalOutput_8",
			"DigitalOutput_9","DigitalOutput_10","DigitalOutput_11","DigitalOutput_12","DigitalOutput_13",
			"DigitalOutput_14","DigitalOutput_15","DigitalOutput_16"
			};

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.variable);
		
		// get db name from the globaldata class.
		dbName=((GlobalData)this.getApplicationContext()).getDbName();

		
		Bundle bundle = getIntent().getExtras();
		
		//Agregamos el arreglo de indices
		indexArrayList.addAll(bundle.getIntegerArrayList("indices"));
		
		//En caso de que se hayan seleccionado todas las variables, se ejecuta esta sentencia
		if(bundle.getBoolean("selectall")){
			if((bundle.getStringArrayList("sensor")).size()!=0){
				listArrayList.addAll(bundle.getStringArrayList("sensor"));
			}else{
				listArrayList.addAll(new ArrayList<String>(Arrays.asList(sensor)));
			}
		
		}else
		{
			listArrayList.addAll(bundle.getStringArrayList("sensor"));
		}
//		//get default display height and width
//		Display display = getWindowManager().getDefaultDisplay();
//		height = display.getHeight();								// get default height of the screen
//		Log.d("System out", "desh height "+ height+ "Width "+display.getWidth());
		
		linearLayout = (LinearLayout)findViewById(R.id.middleVariable);	// mapped with the xml
		listView = new ListView(this);									// this will hold all the variable list with the led on right of it.							
		listView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		
		listArr = (String[])(listArrayList.toArray(new String[listArrayList.size()]));

		// this will create custom list view with two led's on right of the variable name. 
		myArrayAdapter = new MyArrayAdapter(this,listArr);	
		listView.setAdapter(myArrayAdapter);
		listView.setFocusable(true);					
		listView.setBackgroundColor(Color.WHITE);			// set background color white	
		listView.setCacheColorHint(Color.TRANSPARENT);    	// this will not make list view black when we scroll up and down
		linearLayout.addView(listView);						// add list view to the layout
	}

	/*
	 * Below is the class which will create custom list view. 
	 */
	
	public class MyArrayAdapter extends ArrayAdapter<String> {

		private final Activity context;
		//Arreglo con todas las variables selccionadas
		private final String[] variable1;
		//Falta un arreglo con sus estados asociados
		
		public MyArrayAdapter(Activity context, String[] variable) {
			super(context, R.layout.ledlist, variable);
			this.context=context;
			this.variable1=variable;
		}
		/*
		 * (non-Javadoc)
		 * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView = inflater.inflate(R.layout.ledlist, null, true);
			TextView variableTextView = (TextView) rowView.findViewById(R.id.variabletxt);
			variableTextView.setText(variable1[position]);

			ImageView normalImageView = (ImageView)rowView.findViewById(R.id.normalImg);
			ImageView highImageView = (ImageView)rowView.findViewById(R.id.highImg);

			if(statusArrayList.size()!=0){
				
				for(int i=0; i<listArr.length;i++){
					//Aqui es solo para detectar la variable correspondiente con la posicion de la vista a renderizar
					if(variable1[i].equalsIgnoreCase(variable1[position])){
//						if(statusArrayList.get(i).equalsIgnoreCase("normal")&& variable1[i].equalsIgnoreCase(variable1[position])){
//							normalImageView.setBackgroundResource(R.drawable.ledgreenon);
//							highImageView.setBackgroundResource(R.drawable.ledredoff);
//						}else if((statusArrayList.get(i).equalsIgnoreCase("not normal") || statusArrayList.get(i).equalsIgnoreCase("alert"))&& variable1[i].equalsIgnoreCase(variable1[position])){
//							normalImageView.setBackgroundResource(R.drawable.ledgreenoff);
//							highImageView.setBackgroundResource(R.drawable.ledredon);
//						}
						
						if(statusArrayList.get(indexArrayList.get(i)).equalsIgnoreCase("normal")&& variable1[i].equalsIgnoreCase(variable1[position])){
							normalImageView.setBackgroundResource(R.drawable.ledgreenon);
							highImageView.setBackgroundResource(R.drawable.ledredoff);
						}else if((statusArrayList.get(indexArrayList.get(i)).equalsIgnoreCase("not normal") || statusArrayList.get(indexArrayList.get(i)).equalsIgnoreCase("alert"))&& variable1[i].equalsIgnoreCase(variable1[position])){
							normalImageView.setBackgroundResource(R.drawable.ledgreenoff);
							highImageView.setBackgroundResource(R.drawable.ledredon);
						}
						
					}//fin if
					
				}//fin for
				
			
			}
			
			return rowView;
		}		
	}

	/*
	 * this method will get data from the url and will store it in status array list.
	 */
	public void GetData(){
		try{
			// every time this class is getting called so we clear arrylist and store new data in to the array list.
			statusArrayList.clear();				
			statusBoolArrayList.clear();
			// complete url with db name to get data for dash board.
			String urlStr = ("http://megan.teksar.com.mx/jsonmax.php?dbname="+dbName+"&action=select").replaceAll(" ", "%20");
			URL url = new URL(urlStr);									// create new url object
			HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); // http request to get data from the internet
			InputStream in = httpURLConnection.getInputStream();					// get stream data from internet
			BufferedReader br = new BufferedReader(new InputStreamReader(in));			// buffered all the input stream
			String lineBuffer = null ;										// to store buffered data line by line which will be appended in string buffer for json parsing
			jsonText = new StringBuffer();											
			// repeat the while loop untill we read all data from the buffered reader.
			do{		
				lineBuffer = br.readLine();							// read buffer line by line and store in string buffer
				jsonText.append(lineBuffer);
			}while(lineBuffer!=null);

			//comienza el parseo del objeto json
			jsonArray= new JSONArray(jsonText.toString());
			
			for(int i=0; i<jsonArray.length();i++){
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				status = jsonObject.getString("status");
				statusArrayList.add(status);
				
				//aqui dependiendo del estado normal -> true,  not normal o alert -> false
				if(status.equalsIgnoreCase("normal")){
					statusBoolArrayList.add(true);
				}else{
					statusBoolArrayList.add(false);
				}
			}
			
			httpURLConnection.disconnect();
			br.close();
		}catch (Exception e){
			// TODO: handle exception
			e.printStackTrace();
		}
		handlerFlag = true;		
		handler.sendMessage(handler.obtainMessage());
	}

	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			//			super.handleMessage(msg);
			if(handlerFlag){
				myArrayAdapter.notifyDataSetChanged();
			}
		}
	};

	void setRunning(boolean b){
		running = b;
	}
/*
 * (non-Javadoc)
 * @see android.app.Activity#onStart()
 * this method will be called as soon as activity started and start back ground thread.
 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

//				Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();
		backgroundThread = new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(running){
					try {
						Thread.sleep(sleepTime);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					GetData();
					sleepTime = 10000;
				}
			}
		});
		setRunning(true);
		backgroundThread.start();
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 * when activity finish this method will be called and background thread will be stopped.
	 */
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		boolean retry = true;
		setRunning(false);

		while(retry){
			try {
				backgroundThread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
		DeshboardActivity.this.finish();
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 * this will be called when user pressed back button of the device and user will be navigated to previous screen
	 */
	
	public boolean onKeyDown(int keyCode, KeyEvent event){
		super.onKeyDown(keyCode, event);
		if(keyCode == KeyEvent.KEYCODE_BACK){
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), SelectVariable.class);
			startActivity(intent);
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 * this method is used to create menu to change db and close application.
	 */
	
	public boolean onCreateOptionsMenu (Menu menu){
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.option, menu);
		return true;
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	
	public boolean onOptionsItemSelected(MenuItem menuItem){
		
		switch (menuItem.getItemId()) {
		
		case R.id.menuDb:
			((GlobalData)this.getApplicationContext()).setLoginFlag(false);
			((GlobalData)this.getApplicationContext()).setMenuNo(100);
			DeshboardActivity.this.finish();
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ConfigurationActivity.class);
			startActivity(intent);
			break;
		case R.id.menuExit:
			DeshboardActivity.this.finish();
			break;
		}
		return true;
	}
}
